package com.clean.notification.app

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.util.Log
import com.blankj.utilcode.util.SPUtils

class LifecycleMonitor {

    private var resumeActivityCount = 0
    private var application: Application? = null

    fun register(application: Application?) {
        this.application = application
        application?.registerActivityLifecycleCallbacks(object :
            ActivityLifecycleCallbacksAdapter() {
            override fun onActivityStarted(activity: Activity) {
                if (resumeActivityCount++ == 0) {
                    // 执行切换到前台的逻辑
                    Log.e("tag", "后台 --> 前台$resumeActivityCount")
                    SPUtils.getInstance().put("isForeground", true)
                }
            }

            override fun onActivityStopped(activity: Activity) {
                if (--resumeActivityCount == 0) {
                    // 执行切换到后台的逻辑
                    Log.e("tag", "前台 --> 后台$resumeActivityCount")
                    SPUtils.getInstance().put("isForeground", false)
                }
            }
        })
    }

    /**
     * Activity 生命周期监听，用于监控app前后台状态切换(对应Activity生命周期)
     */
    open class ActivityLifecycleCallbacksAdapter : Application.ActivityLifecycleCallbacks {
        override fun onActivityCreated(
            activity: Activity, bundle: Bundle?
        ) {
        }

        override fun onActivityStarted(activity: Activity) {}
        override fun onActivityResumed(activity: Activity) {}
        override fun onActivityPaused(activity: Activity) {}
        override fun onActivityStopped(activity: Activity) {}
        override fun onActivitySaveInstanceState(
            activity: Activity, bundle: Bundle
        ) {
        }

        override fun onActivityDestroyed(activity: Activity) {}
    }

    companion object {
        private var lifecycleHelper: LifecycleMonitor? = null
        val instance: LifecycleMonitor?
            get() {
                if (lifecycleHelper == null) {
                    lifecycleHelper = LifecycleMonitor()
                }
                return lifecycleHelper
            }
    }
}